//
//  DiscoverViewController.m
//  AAIM
//
//  Created by awh on 2019/11/24.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "DiscoverViewController.h"

#import <WebKit/WebKit.h>
#import "FuchuangContentView.h"
#import "WebViewController.h"
@interface DiscoverViewController ()<WKUIDelegate,WKNavigationDelegate,UIGestureRecognizerDelegate,FuchuangContentViewDelegate>
{
    UIButton * markRightBtn;
    UIButton * markBackBtn;
    UIButton * markFuchuangBtn;
}
//@property (nonatomic,strong)UIWebView * contentWebView;
@property (nonatomic,strong)WKWebView * contentWebView;


@property (nonatomic,strong)UserModel * model;
@property (nonatomic,strong)NSString * urlStr;
@property (nonatomic,strong)UIButton *spButton;
@property (nonatomic,strong)UIView * menuBackView;
@property (nonatomic,strong)UIView * fuChuangBackView;

//标记为浮窗后的内容
@property (nonatomic,strong)NSString * markUrl;
@property (nonatomic,strong)NSString * markTitle;
@property (nonatomic,strong)NSMutableArray * markAry;
@end

@implementation DiscoverViewController

//悬浮窗按钮
- (void)addEvent:(UIButton *)sender{
    if (_markAry.count >5) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:@"浮窗已满，清理后可继续新增" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * ok = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:ok];
        return;
    }
    if (_markTitle &&_markUrl) {
        NSDictionary * dic=@{@"url":_markUrl,@"title":_markTitle};
        [self.markAry addObject:dic];
    }
   
    self.fuChuangBackView.hidden = NO;
    [self creatContentView];
}

- (void)creatContentView{
    for (int i=0; i<_markAry.count; i++) {
        NSDictionary * dic = _markAry[i];
        UIImage * image = [UIImage imageNamed:@"我的-头像"];
        FuchuangContentView * contentView=[[FuchuangContentView alloc]initWithFrame:CGRectMake(kScreenWidth-278.f, kScreenHeight/2, 278.f, 60.f) withTitle:dic[@"title"] withImg:image];
        contentView.closeBtn.tag = 500+i;
        contentView.delegate = self;
        contentView.tag = 500+i;
        contentView.openUrlBtn.tag = 500+i;
        contentView.backgroundColor = [UIColor whiteColor];
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:contentView.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerTopLeft  cornerRadii:CGSizeMake(30,30)];
        //创建 layer
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = contentView.bounds;
        //赋值
        maskLayer.path = maskPath.CGPath;
        contentView.layer.mask = maskLayer;
        [[UIApplication sharedApplication].keyWindow addSubview:contentView];
        
    }
}
-(void)openUrlTouchActive:(UIButton *)sender{
    NSDictionary * dic = _markAry[sender.tag-500];
    [self.contentWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",dic[@"url"]]]]];
    WebViewController * vc = [[WebViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    for (int i=0; i<_markAry.count; i++) {
     [[[UIApplication sharedApplication].keyWindow viewWithTag:500+i]removeFromSuperview];
    }
    [_markAry enumerateObjectsUsingBlock:^(NSDictionary * dic, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([_markUrl isEqualToString:dic[@"url"]]) {
            [_markAry removeObjectAtIndex:idx];
        }
    }];


    self.fuChuangBackView.hidden = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)closerFuChuang:(UIButton *)sender{
    NSLog(@"关闭");
    [[[UIApplication sharedApplication].keyWindow viewWithTag:sender.tag]removeFromSuperview];
    [_markAry removeObjectAtIndex:sender.tag-500];
    [self.spButton setTitle:@"" forState:UIControlStateNormal];
    [self.spButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    markRightBtn.selected = NO;
    markFuchuangBtn.selected = NO;
    if (_markAry.count == 0) {
        self.fuChuangBackView.hidden = YES;
        self.spButton.hidden = YES;
    }
}

- (void)hiddenFuChuang{
    for (int i=0; i<_markAry.count; i++) {
     [[[UIApplication sharedApplication].keyWindow viewWithTag:500+i]removeFromSuperview];
    }
    [_markAry enumerateObjectsUsingBlock:^(NSDictionary * dic, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([_markUrl isEqualToString:dic[@"url"]]) {
            [_markAry removeObjectAtIndex:idx];
        }
    }];


    self.fuChuangBackView.hidden = YES;
}

//##pragma标记 - WKNavigationDelegate

//页面开始加载时调用

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    [self showAlwaysTipHudWithText:@"加载中,请稍等!"];
    
}

//当内容开始返回时调用

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
    
    
}

//页面加载完成之后调用

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

    [self hideHud];
    
}

//页面加载失败时调用

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    [self showTipHudWithText:@"网络错误,稍后再试"];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    //网页标题
    if([keyPath isEqualToString:@"title"])
    {
        if(object == self.contentWebView)
        {
            self.gk_navTitle = self.contentWebView.title;
            _markTitle = self.contentWebView.title;
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }

}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if(!navigationAction.targetFrame.isMainFrame){
        [webView loadRequest:navigationAction.request];
    }
    return nil;
    
}

//接收到服务器跳转请求之后调用

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {



}

//在收到响应后,决定是否跳转

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse :( WKNavigationResponse *)navigationResponse decisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler {



//NSLog(@"％@",navigationResponse.response.URL.absoluteString);

//允许跳转

decisionHandler(WKNavigationResponsePolicyAllow);

//不允许跳转

// decisionHandler(WKNavigationResponsePolicyCancel);

}

//在发送请求之前,决定是否跳转

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction :( WKNavigationAction *)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {


//NSLog(@"=================%@========",navigationAction.request.URL.absoluteString);
//
///**
//
// *拦截app跳转
//
// * */
//
NSString * string = navigationAction.request.URL.absoluteString;
    if ([string isEqualToString:self.urlStr]) {
        markBackBtn.hidden = YES;
    }else{
        markRightBtn.selected = NO;
        _menuBackView.hidden = YES;
        markBackBtn.hidden = NO;
        markFuchuangBtn.selected = NO;
    }
    _markUrl = string;

//允许跳转

decisionHandler(WKNavigationActionPolicyAllow);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    //处理任何可以重新创建的资源。
    
}



- (void)jianyuanjiao:(UIButton *)btn withRoundingCorners:(NSInteger)roundingCorners{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:btn.bounds byRoundingCorners:roundingCorners  cornerRadii:CGSizeMake(26,26)];
    //创建 layer
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = btn.bounds;
    //赋值
    maskLayer.path = maskPath.CGPath;
    btn.layer.mask = maskLayer;
}

-(void)initAddEventBtn{
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-52,300,52,52)];
//    [btn setImage:[UIImage imageNamed:@"悬浮窗"]  forState:UIControlStateNormal];
    btn.backgroundColor = KHEXCOLOR(@"#F4F4F4");
    [btn setTitleColor:KHEXCOLOR(AllBackColor_titleColor) forState:UIControlStateNormal];
    btn.titleLabel.font = kMainFont(14.f);
    btn.tag = 0;
    [self jianyuanjiao:btn withRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft];
//    btn.layer.cornerRadius = 8;
    [self.view addSubview:btn];
    self.spButton = btn;
    _spButton.hidden = YES;
    [_spButton addTarget:self action:@selector(addEvent:) forControlEvents:UIControlEventTouchUpInside];
    //添加手势
    UIPanGestureRecognizer *panRcognize=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [panRcognize setMinimumNumberOfTouches:1];
    [panRcognize setEnabled:YES];
    [panRcognize delaysTouchesEnded];
    [panRcognize cancelsTouchesInView];
    [btn addGestureRecognizer:panRcognize];
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)recognizer
{
    //移动状态
    UIGestureRecognizerState recState =  recognizer.state;
    [self jianyuanjiao:self.spButton withRoundingCorners:UIRectCornerAllCorners];
    switch (recState) {
        case UIGestureRecognizerStateBegan:
            
            break;
        case UIGestureRecognizerStateChanged:
        {
            CGPoint translation = [recognizer translationInView:self.navigationController.view];
            recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            CGPoint stopPoint = CGPointMake(0, SCREEN_HEIGHT / 2.0);
            
            if (recognizer.view.center.x < SCREEN_WIDTH / 2.0) {
                if (recognizer.view.center.y <= SCREEN_HEIGHT/2.0) {
                    //左上
                     [self jianyuanjiao:self.spButton withRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight];
                    if (recognizer.view.center.x  >= recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, self.spButton.width/2.0+self.gk_navigationBar.bottom);
                    }else{
                        stopPoint = CGPointMake(self.spButton.width/2.0, recognizer.view.center.y+self.gk_navigationBar.bottom);
                    }
                }else{
                    //左下
                    [self jianyuanjiao:self.spButton withRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight];
                    if (recognizer.view.center.x  >= SCREEN_HEIGHT - recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, SCREEN_HEIGHT - self.spButton.width/2.0);
                    }else{
                        stopPoint = CGPointMake(self.spButton.width/2.0, recognizer.view.center.y);
                        //                        stopPoint = CGPointMake(recognizer.view.center.x, SCREEN_HEIGHT - self.spButton.width/2.0);
                    }
                }
            }else{
                if (recognizer.view.center.y <= SCREEN_HEIGHT/2.0) {
                    //右上
                    [self jianyuanjiao:self.spButton withRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight];
                    if (SCREEN_WIDTH - recognizer.view.center.x  >= recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, self.spButton.width/2.0+self.gk_navigationBar.bottom);
                    }else{
                        stopPoint = CGPointMake(SCREEN_WIDTH - self.spButton.width/2.0, recognizer.view.center.y+self.gk_navigationBar.bottom);
                    }
                }else{
                    //右下
                    [self jianyuanjiao:self.spButton withRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight];
                    if (SCREEN_WIDTH - recognizer.view.center.x  >= SCREEN_HEIGHT - recognizer.view.center.y) {
                        stopPoint = CGPointMake(recognizer.view.center.x, SCREEN_HEIGHT - self.spButton.width/2.0);
                    }else{
                        stopPoint = CGPointMake(SCREEN_WIDTH - self.spButton.width/2.0,recognizer.view.center.y);
                    }
                }
            }
            
            //如果按钮超出屏幕边缘
            if (stopPoint.y + self.spButton.width+40+kTopHeight>= SCREEN_HEIGHT) {
                stopPoint = CGPointMake(stopPoint.x, SCREEN_HEIGHT - self.spButton.width/2.0-self.tabBarController.tabBar.height);
                NSLog(@"超出屏幕下方了!!"); //这里注意iphoneX的适配。。X的SCREEN高度算法有变化。
            }
            if (stopPoint.x - self.spButton.width/2.0 <= 0) {
                 [self jianyuanjiao:self.spButton withRoundingCorners:UIRectCornerTopRight|UIRectCornerBottomRight];
                stopPoint = CGPointMake(self.spButton.width/2.0, stopPoint.y);
            }
            if (stopPoint.x + self.spButton.width/2.0 >= SCREEN_WIDTH) {
                [self jianyuanjiao:self.spButton withRoundingCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft];
                stopPoint = CGPointMake(SCREEN_WIDTH - self.spButton.width/2.0, stopPoint.y);
            }
            if (stopPoint.y - self.spButton.width/2.0 <= 0) {
                stopPoint = CGPointMake(stopPoint.x, self.spButton.width/2.0);
            }
            
            [UIView animateWithDuration:0.5 animations:^{
                recognizer.view.center = stopPoint;
            }];
        }
            break;
            
        default:
            break;
    }
    
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"看看";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    CGFloat tabBarHeight = self.tabBarController.tabBar.frame.size.height;
    _contentWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, self.gk_navigationBar.bottom, kScreenWidth, kScreenHeight-self.gk_navigationBar.bottom-tabBarHeight)];
    _contentWebView.UIDelegate = self;
    _contentWebView.navigationDelegate = self;
    [self.contentWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:@"DJWebKitContext"];
    [_contentWebView.scrollView setAlwaysBounceVertical:YES];
    _contentWebView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contentWebView];
     [self showAlwaysTipHudWithText:@"加载中,请稍等!"];
    [self initAddEventBtn];
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"icon- 点点"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnDidClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn sizeToFit];
    rightBtn.frame = CGRectMake(0, 0, 44, 44);
    rightBtn.tag = 1000001;
    rightBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(10, 10, 10, 10);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.gk_navRightBarButtonItem = rightItem;
    [[UIApplication sharedApplication].keyWindow addSubview:self.menuBackView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.fuChuangBackView];
    self.gk_navigationItem.hidesBackButton = YES;
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"icon-返回键"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backacrion) forControlEvents:UIControlEventTouchUpInside];
    [backBtn sizeToFit];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    backBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(10, 10, 10, 10);
    markBackBtn = backBtn;
    backBtn.hidden = YES;
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.gk_navLeftBarButtonItem = backItem;
    
}

- (void)backacrion{
    
    if ([self.contentWebView canGoBack]) {
        
        /// 网页可以返回 就进行网页返回
        
        [self.contentWebView goBack];
        
    }else{
        
        [self.view resignFirstResponder];
        
        /// 网页返回到首页了 返回不了了 这时候我们的控制器返回
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }

}

-(void)rightBtnDidClickAction:(UIButton*)sender
{
    markRightBtn = sender;
    self.menuBackView.hidden = sender.selected;
    sender.selected = !sender.selected;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.menuBackView.hidden = YES;
    markRightBtn.selected = NO;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDiscoverData];
}

- (void)getDiscoverData{
    _model = [LoginManager shareLoginManager].userModel;
    KWeakSelf;
    [RequestData PostDiscoverWithToken:_model.token userUUid:_model.uuid Success:^(NSDictionary * _Nonnull Dict) {
        NSLog(@"发现接口:%@",Dict);
        if ([Dict[@"code"] integerValue] == 200) {
            weakSelf.urlStr = Dict[@"data"];
            [self.contentWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",weakSelf.urlStr]]]];
        }
    } failure:^(NSString * _Nonnull errMsg) {
        if (errMsg) {
            [self showTipHudWithText:errMsg];
        }else{
            [self showTipHudWithText:@"网络错误"];
        }
    }];
}


- (void)creatFuchuang:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.spButton setTitle:self.gk_navTitle forState:UIControlStateNormal];
        self.spButton.hidden = NO;
    }else{
        self.spButton.hidden = YES;
        //取消所有的悬浮内容
    }
}

//- (WKWebView *)contentWebView{
//    if (!_contentWebView) {
//        CGFloat tabBarHeight = self.tabBarController.tabBar.frame.size.height;
//        _contentWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, self.gk_navigationBar.bottom, kScreenWidth, kScreenHeight-self.gk_navigationBar.bottom-tabBarHeight)];
//        _contentWebView.UIDelegate = self;
//        _contentWebView.navigationDelegate = self;
//        [self.contentWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:@"DJWebKitContext"];
//        [_contentWebView.scrollView setAlwaysBounceVertical:YES];
//        _contentWebView.backgroundColor = [UIColor whiteColor];
//    }
//    return _contentWebView;
//}

- (UIView *)menuBackView{
    if (!_menuBackView) {
        _menuBackView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-147.f,self.gk_navigationBar.bottom-6, 128, 36)];
        
        _menuBackView.layer.cornerRadius = 6;
        _menuBackView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.17].CGColor;
        _menuBackView.layer.shadowOffset = CGSizeMake(4,4);//阴影偏移量
        _menuBackView.layer.shadowOpacity = 1;
        _menuBackView.layer.shadowRadius = 4;
        _menuBackView.backgroundColor = [UIColor whiteColor];
        _menuBackView.hidden  = YES;
        UIButton * fuchuangBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        fuchuangBtn.frame = CGRectMake(0, 0, _menuBackView.width, _menuBackView.height);
        [fuchuangBtn setImage:[UIImage imageNamed:@"悬浮窗"] forState:UIControlStateNormal];
        [fuchuangBtn setTitle:@"打开浮窗" forState:UIControlStateNormal];
        [fuchuangBtn setTitle:@"关闭浮窗" forState:UIControlStateSelected];
        fuchuangBtn.titleLabel.font = kMainFont(16);
        markFuchuangBtn = fuchuangBtn;
        [fuchuangBtn setTitleColor:KHEXCOLOR(@"#262B2F") forState:UIControlStateNormal];
        [fuchuangBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, -5)];
        [fuchuangBtn addTarget:self action:@selector(creatFuchuang:) forControlEvents:UIControlEventTouchUpInside];
        [_menuBackView addSubview:fuchuangBtn];
    }
    return _menuBackView;
}

- (UIView *)fuChuangBackView{
    if (!_fuChuangBackView) {
        _fuChuangBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _fuChuangBackView.backgroundColor = KHEXCOLOR(@"000000");
        _fuChuangBackView.alpha = 0.5;
        _fuChuangBackView.hidden = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenFuChuang)];
        tap.numberOfTouchesRequired =1;
        tap.numberOfTapsRequired = 1;
        [_fuChuangBackView addGestureRecognizer:tap];
    }
    return _fuChuangBackView;
}

- (void)dealloc {
    
    [self.contentWebView removeObserver:self forKeyPath:@"title" context:@"DJWebKitContext"];
    self.contentWebView.scrollView.delegate = nil;
    self.contentWebView.UIDelegate = nil;
    self.contentWebView.navigationDelegate = nil;
    [self.contentWebView stopLoading];
}

- (NSMutableArray *)markAry{
    if (!_markAry) {
        _markAry = [NSMutableArray array];
    }
    return _markAry;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
